<template>
  <div class="doc_room">
    <main ref="main">
      <div
        v-for="(item,index) in chatList"
        :key="index"
        :class="item.fromid===user.id? 'my' : 'patient' "
      >
        <img
          :src="getImageUrl(item.fromid === user.id ? user.avatar : patient.avatar,item.fromid === user.id ? user.gender : patient.gender)"
          alt
          class="avatar"
        />
        <div class="content">
          <p v-if="item.message.type===1">{{item.message.content}}</p>
          <img v-if="item.message.type===2" :src="item.message.content" alt />
          <video :src="item.message.content" v-if="item.message.type===3"></video>
        </div>
        <span class="sendtime">{{moment(item.sendtime).local('zh-cn').format('LTS')}}</span>
      </div>
      <div ref="foot"></div>
    </main>

    <div class="input">
      <Upload action :on-change="uploadImg" :auto-upload="false" :show-file-list="false">
        <i class="el-icon-picture" style="font-size: 25px" />
      </Upload>
      <Input :rows="1" class="message" v-model="value" placeholder="输入发送内容" />
      <Button type="primary" @click="sendText">发送</Button>
    </div>
    <!-- 聊天窗口 -->
    <div id="video-div" class="hiden">
      <Button @click="stopTrack" style="z-index:99">关闭</Button>
      <video id="remote-video" :class="videoChange ? 'big-video' : 'small-video'" autoplay />
      <video
        id="local-video"
        :class="videoChange ? 'small-video' : 'big-video'"
        @click="change"
        autoplay
      ></video>
    </div>
  </div>
</template>

<script>
import { Button, Upload, Input, Message } from 'element-ui'
import { startVideoTalk, stopVideoTalk, onFallEvent } from '@/api/api/DOCwebsocket';
import { getImageUrl, getDInquiry } from '@/api/api'
import moment from 'moment'
export default {
  components: {
    Input,
    Button,
    Upload
  },
  props: ['inquiryid', 'patient'],
  data() {
    return {
      videoChange: true,
      inquiry: {},
      user: JSON.parse(localStorage.getItem('doc_per')),
      currentDoctor: '刘淑华',
      chatList: [],
      type: 1,
      value: '',
      file: null
    }
  },
  async created() {
    this.user.gender = this.user.sex === '男' ? 1 : 0
    this.user.id = this.user._id
    onFallEvent.onClose = (msg) => {
      document.getElementById('video-div').className = 'hiden';
    }
    if (this.inquiryid) {
      this.init();
    }
  },
  mounted() {
    // if (this.patient)
    // const { id } = this.patient
    console.log(this.patient, 'patient---msg')
    this.$nextTick(() => {
      // console.log(this.patient.id, 'patient_id')
      startVideoTalk(this.patient.id).then();
    })
    console.log(this.user, 'info---')
  },
  methods: {
    moment,
    async init() {
      if (this.inquiryid) {
        await this.getInquiry(this.inquiryid);
        this.getChatHistory(this.inquiryid)
      }
    },
    getInquiry(id) {
      getDInquiry({ _id: id }).then(res => {
        if (res.code === 200) {
          this.inquiry = res.data[0]
        }
      })
    },
    getChatHistory(id) {
      //   console.log(this.$store.state.)
      if (!this.$store.state.doctorStore.messageList[id]) {
        this.$store.state.doctorStore.messageList[id] = [];
      }
      console.log(this.$store.state.doctorStore, 'docstore')
      this.chatList = this.$store.state.doctorStore.messageList[id]
    },
    getImageUrl,
    stopTrack() {
      document.getElementById('video-div').className = 'hiden';
      stopVideoTalk();
    },
    change() {
      // 切换屏幕大小
      this.videoChange = !this.videoChange;
    },
    sendMessage(message) {
      // 发送消息
      const data = {
        inquiryid: this.inquiry._id,
        fromid: localStorage.getItem('doctor_id'),
        toid: this.inquiry.patientid,
        message: message
      };
      console.log(data)
      //   console.log(this.$store)
      this.$store.dispatch('doctorStore/sendMessage', data);
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let imgResult = '';
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    },
    uploadImg(file) {
      this.getBase64(file.raw).then(res => {
        const message = {
          type: 2,
          content: res
        };
        this.sendMessage(message);
      });
    },
    sendText() {
      if (this.value.trim().length === 0) {
        Message({
          message: '请输入发送内容',
          type: 'warning'
        });
        return;
      }
      const message = {
        type: 1,
        content: this.value
      };
      this.sendMessage(message);
      this.value = '';
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.main.scrollTop = this.$refs.foot.offsetTop;
    });
  },
  watch: {
    inquiryid: {
      immediate: true,
      handler(val) {
        this.inquiryid = val;
        this.init();
        if (this.patient) {
          this.$nextTick(() => {
            startVideoTalk(this.patient.id).then();
          })
        }
      }
    },
    patient: {
      immediate: true,
      handler(val) {
        this.patient = val;
        this.init();
        this.$nextTick(() => {
          startVideoTalk(this.patient.id).then();
        })
      }
    }
  }
}
</script>

<style lang="scss">
.chatroom{
  .content{
    line-height: 30px;
  }
  span{
    line-height: 0px;
  }
  div{
    align-items: center;
  }
}
.doc_room {
  height: 100%;
  background: #fff;
  position: relative;
  /* z-index:10; */
  main {
    /* flex: 1; */
    height: 450px;
    overflow-y: scroll;
    overflow-x: hidden;
    background: #f3f3f3;
    > div {
      width: 100%;
      padding-top: 10px;
      list-style: none;
      background: #f3f3f3;
      /* clear: both; */
      display: flex;
      // align-items: flex-start;
      > .avatar {
        width: 50px;
        height: 50px;
        margin: 10px 7px;
        border-radius: 50%;
      }
      .content {
        max-width: 50%;
        background: #fff;
        padding: 10px;
        border-radius: 8px;
        font-size: 20px;
        margin: 6px 8px;
        img {
          width: 100%;
        }
      }
      .sendtime {
        font-size: 12px;
        display: inline-block;
        margin-top: 10px;
      }
      &.my {
        flex-direction: row-reverse;
      }
    }
  }
  .input {
    width: 100%;
    /* z-index: 999; */
    height: 50px;
    align-items: center;
    display: flex;
    padding: 0 20px;
    .message {
      flex: 3;
      outline: none;
      margin: 0 20px;
    }
    .btn_send {
      margin-left: 0.4rem;
      background: rgb(32, 168, 221);
      color: #fff;
      outline: none;
      border: none;
      font-size: 14px;
    }
  }
}
#video-div {
  position: absolute;
  right: 0px;
  bottom: 0;
  height: 40%;
  width: 100%;
  button {
    position: absolute;
    right: 0;
    top: 0;
  }
}

#video-div .small-video {
  width: 30%;
  height: 30%;
  position: absolute;
  bottom: 0px;
  right: 0;
}

#video-div .big-video {
  width: 100%;
  height: 100%;
  position: absolute;
}

.hiden {
  /* display: none; */
  opacity: 0;
  z-index:-1;
}

.show {
  display: block;
  opacity: 1;
  z-index:2
}
</style>
